import cv2
import numpy as np

def merge_videos(video_path1, video_path2, output_path):
    # 打开两个视频文件
    cap1 = cv2.VideoCapture(video_path1)
    cap2 = cv2.VideoCapture(video_path2)

    # 获取视频的帧率和帧大小
    fps = 20
    frame_size = (int(cap1.get(cv2.CAP_PROP_FRAME_WIDTH) * 2), int(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT)))

    # 创建一个新的视频文件
    fourcc = cv2.VideoWriter_fourcc(*'mp4v') 
    out = cv2.VideoWriter(output_path, fourcc, fps, frame_size)

    while(cap1.isOpened() and cap2.isOpened()):
        ret1, frame1 = cap1.read()
        ret2, frame2 = cap2.read()

        if ret1 and ret2:
            # 在左边的画面下方添加文字
            cv2.putText(frame1, 'xmem', (frame1.shape[1]//2, frame1.shape[0]-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
            cv2.putText(frame1, 'xmem', (frame1.shape[1]//2, frame1.shape[0]-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 1, cv2.LINE_AA)
            # 在右边的画面下方添加文字
            cv2.putText(frame2, 'segmentation augmented xmem', (frame2.shape[1]//2-100, frame2.shape[0]-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
            cv2.putText(frame2, 'segmentation augmented xmem', (frame2.shape[1]//2-100, frame2.shape[0]-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 1, cv2.LINE_AA)

            # 水平拼接两个视频的每一帧图像
            merged_frame = np.hstack((frame1, frame2))
            # 将拼接后的图像写入新的视频文件
            out.write(merged_frame)
        else:
            break

    # 关闭视频文件
    cap1.release()
    cap2.release()
    out.release()

# 使用示例
merge_videos('workspace/output_xmem_cat.mp4', 'workspace/output_sat_cat.mp4', 'workspace/cat_merge.mp4')